package top.dopen.home.work.common;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

/**
 * <p>
 *		微信token缓存，未用Redis
 * </p>
 *
 * @Auther Dopen
 * @Date 2020/7/29
 */
@Slf4j
@Component
public class AccessTokenTask {

	private String accessToken;


	private String jsapiTicket;


	@Value("${wechat.ticketUrl}")
	private String ticketUrl;

	@Value("${wechat.accessTokenUrl}")
	private String tokenUrl;

	@Resource
	private RestTemplate template;

	@PostConstruct
	public void init (){
		cronJobSch();
	}
	@Scheduled(cron = "0 0 0/1 * * ?")
	public void cronJobSch() {
		ResponseEntity<String> forEntity = template.getForEntity(tokenUrl, String.class);
		String body = forEntity.getBody();
		if(StringUtils.isEmpty(body)){
			return;
		}
		JSONObject jsonObject = JSON.parseObject(body);
		if(0 == jsonObject.getInteger("errcode")){
			accessToken = jsonObject.getString("access_token");
			log.info("获取token {}" ,accessToken);
		}else{
			log.warn("获取access_token失败，{}",body);
		}
		ticketUrl = ticketUrl.replace("ACCESS_TOKEN",getAccessToken());
		ResponseEntity<String> ticketEntity = template.getForEntity(ticketUrl, String.class);
		String ticketBody = ticketEntity.getBody();
		if(StringUtils.isEmpty(ticketBody)){
			return ;
		}
		JSONObject ticketJsonObject = JSON.parseObject(ticketBody);

		if(0 == ticketJsonObject.getInteger("errcode")){
			jsapiTicket = ticketJsonObject.getString("ticket");
			log.info("获取jsapiTicket {}" ,jsapiTicket);
		}else{
			log.warn("获取ticket失败，{}",ticketBody);
		}
	}
	public String getJsapiTicket() {
		return jsapiTicket;
	}

	/**
	 * TODO 存在线程安全问题 ，未了解企微的AccessToken新旧共存时间
	 * @return
	 */
	public String getAccessToken() {
		if(org.apache.commons.lang3.StringUtils.isBlank(accessToken)){
			throw new NullPointerException("accessToken为空");
		}
		return accessToken;
	}
}
